/*
 * Created on Feb 6, 2007
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package org.pricejd.server;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import josx.rcxcomm.*;

/**
 * @author wjpj
 *
 * This class will facilitate sending commands to the RCX.
 * Method's will return when RCX is done with command.
 */
public class RCXProtocol {
	
	RCXPort port;
	DataOutputStream out;
	DataInputStream in;
	
	public RCXProtocol() {
		int status = 0;
		
		try {
			port = new RCXPort();
		} catch (IOException e) {
			e.printStackTrace();
		}
		out = new DataOutputStream(port.getOutputStream());
		in = new DataInputStream(port.getInputStream());
	}
	
	public int[] gotoPoint(int x, int y) {
		int newX = 0, newY = 0, newDeg = 0;
		
		try {
			System.out.println("Writing.");
			out.writeInt(0);
			out.writeInt(x);
			out.writeInt(y);
			out.flush();
			System.out.println("Done Writing.");
		} catch (IOException e) {
		}
		
		try {
			System.out.println("Reading.");
			newX = in.readInt();
			newY = in.readInt();
			newDeg = in.readInt();
			System.out.println("Done Reading.");
		} catch (IOException e1) {
		}
		System.out.println("Returning.");
		int retval[] = {newX, newY, newDeg};
		return retval;
	}
	
	public int[] travel(int x) {
		int newX = 0, newY = 0, newDeg = 0;
		
		try {
			out.writeInt(1);
			out.writeInt(x);
			out.writeInt(0);
			out.flush();
		} catch (IOException e) {
		}
		
		try {
			newX = in.readInt();
			newY = in.readInt();
			newDeg = in.readInt();
		} catch (IOException e1) {
		}
		
		int retval[] = {newX, newY, newDeg};
		return retval;
	}
	
	public int[] rotate(int deg) {
		int newX = 0, newY = 0, newDeg = 0;
		
		try {
			out.writeInt(2);
			out.writeInt(deg);
			out.writeInt(0);
			out.flush();
		} catch (IOException e) {
		}
		
		try {
			newX = in.readInt();
			newY = in.readInt();
			newDeg = in.readInt();
		} catch (IOException e1) {
		}
		
		int retval[] = {newX, newY, newDeg};
		return retval;
	}
	
	public void done(int deg) {
		int newX = 0, newY = 0, newDeg = 0;
		
		try {
			out.writeInt(3);
			out.writeInt(0);
			out.writeInt(0);
			out.flush();
		} catch (IOException e) {
		}
	}
}